import plupload from 'plupload'
import { getToken } from '@/utils/auth'

let baseUrl = process.env.NODE_ENV === 'development' ? `${process.env.VUE_APP_BASE_API}` : `${process.env.VUE_APP_API_PATH}${process.env.VUE_APP_BASE_API}`

export default {
  data() {
    return {
      multipartParams: {},
      uploadUrl: `${baseUrl}hr/salaryMonth/make/importBySubmission`
    }
  },
  methods: {
    async setUploadParam(up, params = {}) {
      this.multipartParams = params
      up.setOption({
        'url': this.uploadUrl
      })
    },
    async initPlupload({
      container,
      selectFiles,
      mimeTypes = [
        { title: 'Excel files', extensions: 'xls,xlsx' }
      ],
      multiSelection = false,
      params = {}
    }) { // 初始化plupload
    	
      let _this = this
      
      let instance = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: selectFiles,
        url: '',
        multipart_params: {},
        chunk_size: '10mb',
        unique_names: true,
        container: document.getElementById(container),
        filters: {
          max_file_size: '10mb',
          mime_types: mimeTypes,
          prevent_duplicates: true // 不允许选取重复文件
        },
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        multi_selection: multiSelection, // 是否多选 默认单选
        flash_swf_url: '../assets/js/lib/plupload-2.1.2/js/Moxie.swf',
        silverlight_xap_url: '../assets/js/lib/plupload-2.1.2/js/Moxie.xap',
        init: {
          PostInit(up) { // 当Init事件发生后触发监听函数参数：(uploader)
            // console.log(up)
            _this.setUploadParam(up, params)
          },

          FilesAdded(up, files) { // 当文件添加到上传队列后触发监听函数参数：(uploader,files)
            // console.log(up)
            up.start()
          },

          BeforeUpload(up, file) {
            // console.log(file)
            // _this.multipartParams['key'] = _this.ossSignatureInfo['dir'] + file.id
            up.setOption({
              'multipart_params': _this.multipartParams
            })
          },

          UploadProgress(up, file) { // 会在文件上传过程中不断触发，可以用此事件来显示上传进度监听函数参数：(uploader,file)
            console.log(file.percent)
          },

          FileUploaded(up, file, info) { // 当队列中的某一个文件上传完成后触发监听函数参数：(uploader,file,responseObject)
            // _this.setUploadParam(up)
            // console.log(up)
            // console.log(file)
             console.log(info)
            let result = JSON.parse(info.response)
             console.log(result)
            if (+result.code === 200) {
              // console.log(up)
              up.trigger('handleAddFile', result)
            } else {
              _this.$notify.error({
                title: '错误',
                message: result.msg || '上传失败',
                dangerouslyUseHTMLString: true
              })
              // console.log()
            }
          },

          UploadComplete(up, files) { // 当上传队列中所有文件都上传完成后触发监听函数
            // console.log(up)
            // console.log(files)
          },

          Error(up, err) { // 当发生错误时触发监听函数参数：(uploader,errObject)
             console.log(err)
            // console.log(up.removeFile())
            // _this.setUploadParam(up)
            up.removeFile(err.file)
            // console.log(err)
            switch (err.code) {
              case -600:
                _this.$notify.error({
                  title: '错误',
                  message: '选择的文件太大，最大10M!'
                })
                break
              case -601:
                _this.$notify.error({
                  title: '错误',
                  message: '选择的文件类型不符合要求!'
                })
                break
             /* case -602:
                _this.$notify.error({
                  title: '错误',
                  message: '选取了重复的文件!'
                })
                break*/
              default:
                _this.$notify.error({
                  title: '错误',
                  message: '上传失败!'
                })
                // up.removeFile(err.file)
                break
            }
          }
        }
      })

      return new Promise((resolve, reject) => {
        if (instance) {
          resolve(instance)
          console.log('plupload初始化成功！');
        } else {
          throw new Error('plupload初始化出错！')
        }
      })
    }
    
    // 初始化plupload 结束
  }
}
